import React, {Component} from 'react';
import '../../static/home/publicSentiment.styl'
import {timestampToTime} from "../../util/util";
import axios from 'axios'
import {Row, Col,message} from 'antd';
import Loading from '../common/Loading'
import $ from 'jquery'


const Pon = (props) => {
  let bg = ''
  let text = ''
  switch (props.positiveOrNegative) {
    case '1':
      bg = '#62c013'
      text = '正面'
      break
    case '2':
      bg = '#eb4a35'
      text = '负面'
      break
    default:
      bg = '#2184da'
      text = '中性'
  }
  let style = {
    display: 'inline-block',
    height: '8px',
    width: '8px',
    borderRadius: '50%',
    marginRight: '10px',
    background: bg
  }
  return <div>
    <span style={style}></span>
    <span>{text}</span>
  </div>
}

export default class NewsList extends React.Component {
  state = {
    value: 1,
    activeIndex: 0,
    modules: [],
    loaded: false,
    moduleDetails: [],
    details: []
  };

  addActive = (index) => {
    this.setState({
      activeIndex: index,
    });
  }

  queryTodayOpinion = async () => {
    let res = await
      axios.post('vrv-monitor-platform-web/module/queryByOrgCodeHome', {home: 1})
    if (res.data.statusCode === 200) {
      this.setState({
        modules: res.data.data
      }, () => {
        this.make()
        this.queryModuleDetails()
      })
    }
  }

  queryModuleDetails = () => {
    this.state.modules.forEach((item, i) => {
      // this.setState((prevState) => ({
      //   details: [...prevState.details, {loaded: false, module: []}]
      // }))
      axios.get('vrv-monitor-platform-web/module/query', {
        params: {
          moduleId: item.id
        }
      }).then(module => {
        this.setState((prevState) => ({
          moduleDetails: [...prevState.moduleDetails, module.data.data !== null ? module.data.data : []]
        }))
      })
    })
  }
  // 页面动画
  make=()=>{
    // let lists = this.$refs.menuItem
    // let topbar = this.$refs.topbar
    let w =  this.refs.modules.clientWidth
    let _this = this
    // $(lists).each(function(i, el){
    //   el.style.background = `hsl(${Math.random() * 360}, 60%, 70%)`
    // })
    $.fn.gridup = function(
      {
        width = (w-20)/2,
        height = 381,
        wgap = 20,
        hgap = 20,
        colnum = 2,
        transition = 500,
        data = []
      } = {}){
      let m = document.body.clientWidth
      if(m<1600&m>1300){
        height = 358
      }else if(m<1300){
        height = 308
      }
      let $el = this.eq(0)
      let $bg = $('<div class="m-gridup-bg"></div>')
      let $items = $el.children()
      let len = $items.length
      let $tmp
      let elpos
      let mdpos
      let mdflag = false
      let mz = 10
      let timer = {last: 0, curr: +new Date()}
      let getTopLeft = function({col, row}){
        return {
          left: col * (width + wgap),
          top: row * (height + hgap)
        }
      }
      $el.addClass('m-gridup')
      $el.css({
        width: colnum * (width + wgap) - wgap,
        height: Math.ceil(len / colnum) * (height + hgap) - hgap
      })
      $bg.css({width,height})
      $el.prepend($bg)
      elpos = $el.offset()
      if(data.length >= len){
        $items.each((i, el) => $(el).data('d', data[i]))
      }
      $items.addClass('m-gridup-item')
      $items.css({
        width,
        height,
        transitionDuration: transition + 'ms'
      })
      $items.each(function(i, el){
        let row = Math.floor(i / colnum)
        let col = i % colnum
        let $el = $(el)
        $el.css(getTopLeft({col, row}))
        $el.data('pos', {row, col})
      })
      $items.on('mousedown', function(e){
        $tmp = $(this)
        let tmppos = $tmp.position()
        $bg.css(getTopLeft($tmp.data('pos')))
        mdpos = {
          x:e.pageX - tmppos.left,
          y:e.pageY - tmppos.top
        }
        $el.css('cursor', '-webkit-grab')
        $tmp.css('transition-duration', '0ms')
        $tmp.css('z-index', mz++)
        mdflag = true
      })
      $el.on('mousemove', function(e){
        if(mdflag){
          let offset = {
            top: e.pageY - mdpos.y,
            left: e.pageX - mdpos.x
          }
          $tmp.css(offset)
          timer.curr = +new Date()
          if(timer.curr - timer.last > 100){
            timer.last = timer.curr
            $items.each(function(i, e){
              let $e = $(e)
              let tpos = $tmp.data('pos')
              let epos = $e.data('pos')
              if(tpos.row == epos.row && tpos.col == epos.col) return
              let toff = getTopLeft(tpos)
              let eoff = getTopLeft(epos)
              let ch = height - Math.abs(eoff.top - offset.top)
              let cw = width - Math.abs(eoff.left - offset.left)
              if(ch > 0 && cw > 0 && ch * cw > width * height * 2 / 5){
                $e.css(toff)
                $bg.css(eoff)
                $tmp.data('pos', epos)
                $e.data('pos', tpos)
              }
            })
          }
        }
      })
      $el.on('mouseup', function(){
        $el.css('cursor', '')
        mdflag = false
        let pos = getTopLeft($tmp.data('pos'))
        $tmp.css(pos)
        $tmp.css('transition-duration', transition + 'ms')
        if(JSON.stringify(arr) != JSON.stringify(grid.getSorted())){
          arr = grid.getSorted()
          _this.changeSeq(grid.getSorted())
        }
      })
      return {
        getSorted(){
          return Array.from($items)
            .map(d => {
              let pos = $(d).data('pos')
              return {
                row: pos.row,
                col: pos.col,
                data: $(d).data('d')
              }
            }).sort((a, b) => a.row == b.row ? a.col - b.col : a.row - b.row)
            .map(d => d.data)
        }
      }
    }
    let modules = this.refs.modules
    let arr = this.state.modules.map(v => v.id)
    let grid = $(modules).gridup({
      data: arr
    })
  }

  changeSeq(arr){
    axios.post('vrv-monitor-platform-web/module/changeSeq',{
      ids:arr.join(',')
    }).then(d=>{
      console.log(d)
    })
  }

  componentDidMount() {
    this.queryTodayOpinion()
  }

  render() {
    return (
      <div className="modules m-gridup" ref="modules">
        {
          !this.state.loaded ?
            this.state.modules.map((item, i) => {
              return <div className="newsList" key={i} >
                <div className="list-head">
                  <div className="list-title">{item.moduleName}（212）</div>
                  <div className="sortBy">
              <span className={this.state.activeIndex === 0 ? 'active' : ''} onClick={() => {
                this.addActive(0)
              }}>最新</span>
                    <span className={this.state.activeIndex === 1 ? 'active' : ''} onClick={() => {
                      this.addActive(1)
                    }}>负面</span>
                    <img src={require('../../static/images/oval.png')} style={{verticalAlign: 'sub'}}/>
                  </div>
                </div>
                {
                  this.state.moduleDetails[i] ?
                      <div style={{height: 280, overflow: 'hidden'}}>
                        {
                          this.state.moduleDetails[i] ?
                            (this.state.moduleDetails[i]).map((item, index) => {
                              return <div className="gutter-list" key={index}>
                                <Row>
                                  <Col className="gutter-row" span={2}>
                                    <div className="gutter-box">
                                      <img className="img-icon"
                                           src='http://bmp.skxox.com/201710/01/qianxunqihua.104157.jpg'/>
                                    </div>
                                  </Col>
                                  <Col className="gutter-row" span={10}>
                                    <div className="gutter-box box">
                                      <div>{item.title}</div>
                                      <div>{item.content}</div>
                                    </div>
                                  </Col>
                                  <Col className="gutter-row" span={3}>
                                    <div className="gutter-box"
                                         style={{textAlign: 'center', color: '#3c496a'}}>
                                      {<Pon positiveOrNegative={item.positiveOrNegative}/>}
                                    </div>
                                  </Col>
                                  <Col className="gutter-row" span={3}>
                                    <div className="gutter-box"
                                         style={{textAlign: 'center', color: '#3c496a'}}>{item.webSite}</div>
                                  </Col>
                                  <Col className="gutter-row" span={6}>
                                    <div className="gutter-box"
                                         style={{
                                           textAlign: 'center',
                                           color: '#3c496a'
                                         }}>{timestampToTime(item.addTime)}</div>
                                  </Col>
                                </Row>
                              </div>
                            }) : ''
                        }
                      </div> : <Loading/>
                }
                <div className="more">
                  <span>查看更多>></span>
                </div>
              </div>
            })
            : <Loading/>
        }
      </div>
    );
  }
}